﻿using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MES.Process.API.Extensions
{
    /// <summary>
     /// EF Core性能优化扩展
     /// </summary>
    public static class EfCoreOptimizationExtensions
    {
        /// <summary>
        /// 配置EF Core性能优化
        /// </summary>
        public static IServiceCollection AddOptimizedEfCore(this IServiceCollection services, IConfiguration configuration)
        {
            // 使用DbContext池优化 减少DbContext实例化成本
            services.AddDbContextPool<MESDBContext>(options =>
            {
                var connectionString = configuration.GetConnectionString("DB");

                // 启用MARS（多活动结果集）
                if (!connectionString.Contains("MultipleActiveResultSets"))
                {
                    connectionString += ";MultipleActiveResultSets=True";
                }

                options.UseSqlServer(connectionString, sqlServerOptions =>
                {
                    // 启用批处理语句优化
                    sqlServerOptions.MaxBatchSize(100);

                    // 启用查询拆分行为
                    sqlServerOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
                })
                .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
                .EnableSensitiveDataLogging(false) // 生产环境关闭敏感数据日志
                .EnableDetailedErrors(false) // 生产环境关闭详细错误
                .ConfigureWarnings(warnings =>
                {
                    // 忽略某些警告以提高性能
                    warnings.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.CoreEventId.FirstWithoutOrderByAndFilterWarning);
                });
            });

            return services;
        }

        /// <summary>
        /// 配置查询跟踪行为
        /// </summary>
        public static void ConfigureQueryTracking(this MESDBContext context)
        {
            // 默认使用非跟踪查询以提高只读性能
            context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            // 关闭自动检测更改以提高批量操作性能
            context.ChangeTracker.AutoDetectChangesEnabled = false;
        }
    }
}
